<template>
  <div>
    <the-table
      :total="state.total"
      :data="state.tableData"
      @search="querySearch"
      @handleExport="exportExcel"
      :pageInfo="state.pageInfo"
      @pageInfoChange="pageInfoChange"
      @handleAdd="state.addDialogVisuble = true"
      @handleImport="state.excelInDialogVisible = true"
      @clearInput="getData"
      :layout="['addBtn', 'search', 'column', 'importBtn', 'exportBtn']"
      :columns="state.columns"
    >
      <el-table-column prop="id" label="院系编号" v-if="state.columns[0].show" />
      <el-table-column prop="name" label="学院名" v-if="state.columns[1].show" />
      <el-table-column prop="univId" label="学校编号" v-if="state.columns[2].show" />
      <el-table-column prop="createTime" label="创建时间" v-if="state.columns[3].show" />
      <el-table-column label="操作" width="230px">
        <template #default="scope">
          <el-button style="color: #67c23a" type="text" size="small" @click="goClass(scope.row.id)">
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>班级管理
          </el-button>
          <el-button
            style="color: #409eff"
            type="text"
            size="small"
            @click="openEditDialog(scope.row)"
          >
            <el-icon class="el-input__icon">
              <edit />
            </el-icon>编辑
          </el-button>
          <el-button
            type="text"
            style="color: #f56c6c"
            size="small"
            @click="deleteById(scope.row.id)"
          >
            <el-icon class="el-input__icon">
              <delete />
            </el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <!-- @open="clearAddForm" -->
    <el-dialog
      title="增加学院信息"
      v-model="state.addDialogVisuble"
      width="30%"
      @close="state.facultyForm.name = ''"
    >
      <el-form label-position="right" label-width="90px" :model="state.facultyForm" ref="formRef">
        <el-form-item label="学院名称" prop="name">
          <el-input v-model="state.facultyForm.name" placeholder="请输入学院名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer #default="scope">
        <span class="dialog-footer">
          <el-button @click="state.addDialogVisuble = false">取 消</el-button>
          <el-button type="primary" @click="addComfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="修改学院信息" v-model="state.editDailogVisible" width="30%">
      <el-form label-position="right" label-width="90px" :model="state.facultyForm" ref="formRef">
        <el-form-item label="学院名称" prop="name">
          <el-input v-model="state.editForm.name" placeholder="请输入学院名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer #default="scope">
        <span class="dialog-footer">
          <el-button @click="state.editDailogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editComfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="导入文件" v-model="state.excelInDialogVisible" width="27%" @open="clearUpload">
      <el-upload
        class="upload-demo"
        drag
        ref="uploadRef"
        :auto-upload="true"
        action="http://112.74.61.241:8081/orgs/depts/batchImportDepts"
        :before-upload="beforeUpload"
        :multiple="false"
        :on-exceed="handleExceed"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        :limit="1"
        :http-request="uploadExcel"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">一次只能上传一个文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="state.excelInDialogVisible = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { addLogs } from '#/Home/Home'
import { ElMessage, ElMessageBox } from 'element-plus'
import TheTable from "@/components/common/TheTable.vue";
import { addFaculty, updateFaculty, deleteFaculty, importBatch, exportBatch, getFacultyPage, searchFacultyPage } from '@/api/OrganizationManagement/faculty'
import _ from 'lodash'
export default defineComponent({
  components: {
    TheTable
  },
  setup() {
    const router = useRouter()
    const state = reactive({
      schoolId: router.currentRoute.value.query.id,
      tableData: [],
      pageInfo: {
        isShow: true,
        pageSize: 5,
        pageNum: 1,
        placeholder: "请输入内容",
      },
      total: 0,
      addDialogVisuble: false,
      editDailogVisible: false,
      excelInDialogVisible: false,
      facultyForm: {
        name: '',
        univId: router.currentRoute.value.query.id
      },
      editForm: {
        name: '',
        univId: router.currentRoute.value.query.id
      },
      editId: "",
      columns: [
        { name: "编号", show: true },
        { name: "院系名", show: true },
        { name: "所属学校", show: true },
        { name: "学校编号", show: true },
        { name: "创建时间", show: true },
      ]
    })
    let uploadRef: any = ref(null)
    const formRef: any = ref(null);    //表单Dom对象ref
    const getData = async (schoolId): Promise<void> => {
      const res: any = await getFacultyPage(schoolId, state.pageInfo.pageNum, state.pageInfo.pageSize)
      if (res.data.ret === 0) {
        state.tableData = res.data.orgs.depts.content
        state.total = res.data.orgs.depts.totalElements
      }
      console.log(res)
    }

    onMounted(() => {
      getData(state.schoolId)
      console.log(state.schoolId)
    })

    const pageInfoChange = (type: string, newValue: number): void => {
      type === 'size' ? state.pageInfo.pageSize = newValue : state.pageInfo.pageNum = newValue;
      getData(state.schoolId)
    }

    const querySearch = async (queryInfo: string): Promise<void> => {
      state.pageInfo.pageNum = 1
      const res: any = await searchFacultyPage(state.schoolId, queryInfo, state.pageInfo.pageNum, state.pageInfo.pageSize)
      console.log(res)
      if (res.data.ret === 0) {
        ElMessage.success('查询成功')
        state.tableData = res.data.orgs.dept.content
        state.total = res.data.orgs.dept.totalElements
      }
    }

    const openEditDialog = (obj): void => {
      console.log(obj)
      state.editId = obj.id
      state.editDailogVisible = true
      state.editForm.name = obj.name
    }

    const deleteById = async (id: string): Promise<void> => {
      const confirmRes = await ElMessageBox.confirm(
        "此操作将永久删除该学院信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err: any) => err);
      if (confirmRes) {
        await deleteFaculty(id).then((res: any) => {
          if (res.data.ret === 0) {
            ElMessage.success('删除成功')
            getData(state.schoolId)
            addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '成功删除了院系信息信息',
            })
          }
        })
      }
    }

    const addComfirm = async (): Promise<void> => {
      await addFaculty(state.facultyForm).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success('创建成功')
          addLogs({
            userId: window.sessionStorage.getItem('userId'),
            behavior: '成功创建院系信息信息',
          })
          getData(state.schoolId)
          state.addDialogVisuble = false
        }
      })
    }

    const editComfirm = async (): Promise<void> => {
      await updateFaculty(state.editId, state.editForm).then((res: any) => {
        console.log(res)
        if (res.data.ret === 0) {
          ElMessage.success('修改成功')
          addLogs({
            userId: window.sessionStorage.getItem('userId'),
            behavior: '成功修改院系信息信息',
          })
          getData(state.schoolId)
          state.editDailogVisible = false
        }
      })
    }

    const exportExcel = async (): Promise<void> => {
      await exportBatch(state.schoolId).then(res => {
        if (res.status === 200) {
          let data: any = res.data
          const blob = new Blob([data], {  // res 为后台返回数据
            type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
          });
          ElMessage.success('导出成功')
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a');
            elink.download = `学院信息.xlsx`;
            elink.style.display = 'none';
            elink.target = '_blank';
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      })
    }

    const beforeUpload = (file: any): any => {
      const isText = file.type === 'application/vnd.ms-excel';
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isText && !isTextComputer) {
        ElMessage.warning('请上传excel格式文件！');
        return
      }
      const fileSize = file.size / 1024 / 1024 < 5
      if (!fileSize) {
        ElMessage.warning('文件大小不能超过5M');
        return
      }
      return (isText || isTextComputer);
    }

    //文件数量超过limit时触发的方法
    const handleExceed = (files, fileList) => {
      console.log(files, fileList)
      ElMessage.warning('当前限制选择 1 个文件，请删除后继续上传');
    }

    const uploadExcel = async (item): Promise<void> => {
      const fileObj = item.file;
      console.log(fileObj)
      const form = new FormData();
      form.append('file', fileObj);
      console.log(form)
      await importBatch(form).then((res: any) => {
        if (res.data.ret === 0) {
          ElMessage.success('文件：' + fileObj.name + res.data.msg);
          getData(state.schoolId)
        }
      }).catch(() => {
        ElMessage.error('文件：' + fileObj.name + '上传失败！');
      })
    }

    const goClass = (id: string): void => {
      router.push('/OrganizationManagement/classManagement?id=' + id)
    }

    const clearUpload = () => {
      nextTick(() => {
        uploadRef.value.clearFiles()
      })
    }
    return {
      state,
      formRef,
      uploadRef,
      getData,
      addComfirm,
      editComfirm,
      openEditDialog,
      deleteById,
      querySearch,
      pageInfoChange,
      exportExcel,
      goClass,
      beforeUpload,
      handleExceed,
      uploadExcel,
      clearUpload
    }
  }

})
</script>
<style>
.el-select {
  width: 120px;
}
.el-input {
  width: 80%;
  padding-right: 50px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-pagination {
  padding-top: 60px;
}
</style>

